/**
 * @Author houlijx
 * @Description //TODO $
 * @Date 2021/8/7 下午1:50
 **/
package ipUtils

import (
	"encoding/binary"
	"github.com/mingrammer/commonregex"
	"net"
	"regexp"
	"strconv"
	"strings"
)

// CheckIpV4
// 检查ipv4是否合法
func CheckIpV4(ipV4 string) bool {
	address := net.ParseIP(ipV4)
	if address == nil {
		return false
	}
	return true
}

// IP2Long
// ip转long
func IP2Long(ipstr string) uint32 {
	ip := net.ParseIP(ipstr)
	if ip == nil {
		return 0
	}
	ip = ip.To4()
	return binary.BigEndian.Uint32(ip)
}

// Long2Ip
// longIP转string ip
func Long2Ip(ipLong uint32) string {
	ipByte := make([]byte, 4)
	binary.BigEndian.PutUint32(ipByte, ipLong)
	ip := net.IP(ipByte)
	return ip.String()
}

// IsRange
// 判断是否在同一网段
func IsRange(ip, cidr string) bool {
	_, ipnet, _ := net.ParseCIDR(cidr)
	ipB := net.ParseIP(ip)
	if ipnet.Contains(ipB) {
		return true
	}
	return false
}

// IpMaskToInt
// 将ip格式的掩码转换为整型数字
// 如 255.255.255.0 对应的整型数字为 24
func IpMaskToInt(netmask string) int {
	ipSplitArr := strings.Split(netmask, ".")
	if len(ipSplitArr) != 4 {
		return 0
	}
	ipv4MaskArr := make([]byte, 4)
	for i, value := range ipSplitArr {
		intValue, err := strconv.Atoi(value)
		if err != nil {
			return 0
		}
		if intValue > 255 {
			return 0
		}
		ipv4MaskArr[i] = byte(intValue)
	}
	ones, _ := net.IPv4Mask(ipv4MaskArr[0], ipv4MaskArr[1], ipv4MaskArr[2], ipv4MaskArr[3]).Size()
	return ones
}

func IsMac(content string) bool {
	var regexMac = "[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}"
	match, _ := regexp.Match(regexMac, []byte(content))
	return match
}

func IsMacV1(content string) bool {
	macList := commonregex.MACAddresses(content)
	if len(macList) > 0 {
		return true
	}
	return false
}

func FetchMac(content string) []string {
	return commonregex.MACAddresses(content)
}
